import time
import sys

from PyQt6 import QtCore, QtGui, QtWidgets
from UI.EM_MainWindow import Ui_MainWindow  # 主窗口UI文件

from plot import TrendChart
from dll_api import *

RUNNING_STYLE = """
QToolButton {
    background-color: rgb(85, 255, 0); 
    color: white; 
    border: 2; 
    border-radius: 25px; 
}
"""

STOPPED_STYLE = """
QToolButton {
    background-color: rgb(213, 213, 213);
    color: red;
    border: 2; 
    border-radius: 25px; 
}
"""

# 轴编号：1-4
axis_num = 1
# 串口，默认0
com_port = 0

# 最小角度
min_angle = -5
# 最大角度
max_angle = 365
# 轴脉冲数
axis_pulses_value = 50000


class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
    def __init__(self):
        super().__init__()
        self.velocity_changed = False
        self.com_status = False
        self.need_reset_x_min = True
        self.pulses = 0
        self.setupUi(self)
        self.trend_chart = TrendChart(self.groupBox)
        self.init_signals()
        self.init_settings()
        self.current_angle = self.doubleSpinBox.value()
        self.update_interval = int(self.doubleSpinBox_2.value() * 1000)
        self.timer = QtCore.QTimer(self)
        self.timer.timeout.connect(self.update_chart)

    def init_signals(self):
        """初始化信号连接"""
        self.pushButton.clicked.connect(self.start_updates)  # 开始更新
        self.pushButton_2.clicked.connect(self.stop_running)  # 停止
        self.doubleSpinBox.valueChanged.connect(self.update_dial)
        self.dial.valueChanged.connect(self.update_double_spin_box)
        self.spinBox_3.editingFinished.connect(self.on_editing_finished)
        self.doubleSpinBox_2.editingFinished.connect(self.on_interval_editing_finished)
        self.toolButton_2.clicked.connect(self.on_button_clicked)

    def on_button_clicked(self, checked):
        if checked:
            self.doubleSpinBox_3.setEnabled(False)
            self.tabWidget.setEnabled(True)

        else:
            self.doubleSpinBox_3.setEnabled(True)
            self.tabWidget.setEnabled(False)

    def on_editing_finished(self):
        """槽函数：当spinBox_3编辑完成时标记速度已更改"""
        self.velocity_changed = True

    def get_velocity(self):
        """从DLL获取当前轴的速度"""
        open_res = wj_api.WJ_Open(com_port)
        if open_res != 0:
            self.spinBox_3.setValue(1)
            self.show_warning_message("打开端口失败")
            return False
        self.com_status = True
        vel = get_axis_velocity(axis_num)
        self.spinBox_3.setValue(vel)
        self.velocity_changed = False
        return True

    def init_settings(self):
        """初始化UI设置"""
        self.setFixedSize(877, 372)
        layout = QtWidgets.QVBoxLayout(self.groupBox)
        layout.addWidget(self.trend_chart)

        label = QtWidgets.QLabel(self.frame_2)
        pixmap = QtGui.QPixmap("dll/logo-small.png")
        label.setPixmap(pixmap)
        label.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)

        label.setSizePolicy(QtWidgets.QSizePolicy.Policy.Expanding, QtWidgets.QSizePolicy.Policy.Expanding)

        label.setScaledContents(True)
        frame_layout = QtWidgets.QVBoxLayout(self.frame_2)
        frame_layout.addWidget(label)
        self.frame_2.setLayout(frame_layout)
        # 设置轴脉冲数
        self.lineEdit.setText(str(axis_pulses_value))
        # 设置最小角度
        self.spinBox_4.setProperty("value", min_angle)
        # 设置最大角度
        self.spinBox_5.setProperty("value", max_angle)
        self.doubleSpinBox.setReadOnly(True)
        self.spinBox_4.setReadOnly(True)
        self.spinBox_5.setReadOnly(True)
        self.lineEdit.setReadOnly(True)
        self.doubleSpinBox.setMinimum(self.spinBox_4.value())
        self.doubleSpinBox.setMaximum(self.spinBox_5.value())
        self.doubleSpinBox_angle.setMinimum(self.spinBox_4.value())
        self.doubleSpinBox_angle.setMaximum(self.spinBox_5.value())
        self.get_velocity()

    def start_updates(self):
        """开始更新图表"""
        self.current_angle = self.doubleSpinBox.value()
        if self.send_run_command():
            self.set_running_style()
            if self.need_reset_x_min:
                self.trend_chart.reset_x_min()
                self.need_reset_x_min = False
            self.timer.start(self.update_interval)

    def update_chart(self):
        """用最新数据更新图表"""
        pulses = get_axis_pulses(axis_num)
        if self.pulses == pulses:
            self.toolButton.setText("已停止")
            self.toolButton.setStyleSheet(STOPPED_STYLE)
        self.pulses = pulses
        move_angle = pulses / int(self.lineEdit.text()) * 360

        real_angle = self.current_angle + move_angle
        if real_angle > 365:
            real_angle -= 360
        if real_angle < -5.1:
            real_angle += 360
        self.doubleSpinBox.setValue(real_angle)
        try:
            self.trend_chart.update_angle(real_angle)
        except Exception as e:
            print(e)
            import traceback
            print(traceback.format_exc())

    def update_dial(self, value):
        """根据doubleSpinBox的值更新dial的值"""
        rounded_value = round(value)
        self.dial.setValue(rounded_value)

    def update_double_spin_box(self, value):
        """根据dial的值更新doubleSpinBox的值"""
        self.doubleSpinBox.setValue(value)

    def set_running_style(self):
        """设置工具按钮样式以指示运行状态"""
        self.toolButton.setText("运行中")
        self.toolButton.setStyleSheet(RUNNING_STYLE)

    def stop_running(self):
        """停止更新并设置工具按钮样式以指示停止状态"""
        self.toolButton.setText("已停止")
        self.toolButton.setStyleSheet(STOPPED_STYLE)
        self.timer.stop()
        emergency_stop_axis(axis_num)
        if self.com_status:
            # 关闭通信
            wj_api.WJ_Close()
            self.com_status = False

    def send_run_command(self):
        """发送运行命令到轴"""
        open_res = 0
        move_pulses = round((self.doubleSpinBox_angle.value() - self.current_angle) * int(self.lineEdit.text()) / 360)
        if not self.com_status:
            open_res = wj_api.WJ_Open(com_port)
        if open_res != 0:
            self.show_warning_message("打开端口失败")
            return False
        if self.velocity_changed:
            print("速度已更改，发送命令...")
            self.velocity_changed = False
            set_axis_velocity(axis_num, self.spinBox_3.value())
        self.com_status = True
        time.sleep(0.2)
        set_axis_pulses_zero(axis_num)
        time.sleep(0.3)
        move_axis_pulses(axis_num, move_pulses)
        return True

    def on_interval_editing_finished(self):
        """槽函数：当doubleSpinBox_2编辑完成时调整定时器间隔"""
        value = self.doubleSpinBox_2.value()
        self.update_interval = int(value * 1000)  # 将秒转换为毫秒
        self.timer.setInterval(self.update_interval)

        print(f"定时器间隔设置为 {self.update_interval} 毫秒")

    def show_warning_message(self, message):
        """
        显示警告消息对话框

        :param message: 警告消息
        """
        msg_box = QtWidgets.QMessageBox()
        msg_box.setIcon(QtWidgets.QMessageBox.Icon.Warning)
        msg_box.setWindowTitle("警告")
        msg_box.setText(message)
        msg_box.setStandardButtons(QtWidgets.QMessageBox.StandardButton.Ok)
        msg_box.exec()


if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    window = MainWindow()
    window.show()
    # 连接aboutToQuit信号到槽函数
    app.aboutToQuit.connect(wj_api.WJ_Close)
    sys.exit(app.exec())
